package com.match.competition_apply.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.match.commonutils.Result;
import com.match.competition_apply.client.CourseClient;
import com.match.competition_apply.entity.CompetitionInfo;
import com.match.competition_apply.entity.vo.CompetitionInfoQuery;
import com.match.competition_apply.service.CompetitionInfoService;
import com.match.competition_apply.utils.CompetitionExcelByHutoolUtils;
import com.match.entity.baseEntity.Teacher;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author AdiosF
 * @since 2021-09-23
 */
@Api(tags = "竞赛基本信息模块")
@RestController
@RequestMapping("/competition_apply/competition-info")
public class CompetitionInfoController {
       @Autowired
       private CompetitionInfoService competitionInfoService;

       @Autowired
       private CourseClient courseClient;

       @ApiOperation("新建竞赛")
       @PostMapping("/addCompetition")
       public Result addCompetition(@ApiParam(required = true,value = "竞赛基本信息")
                                    @RequestBody CompetitionInfo competitionInfo){
           //生成唯一ID
           SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
           Date date = new Date(System.currentTimeMillis());
           Random random = new Random();
           String UUID=formatter.format(date)+random.nextInt(10000);
           competitionInfo.setId(UUID);
           //判断竞赛名称是否唯一
           QueryWrapper<CompetitionInfo> competitionInfoQueryWrapper=new QueryWrapper<>();
           String competitionName = competitionInfo.getCompetitionName();
           if (!StringUtils.isEmpty(competitionName)){
               competitionInfoQueryWrapper.eq("competition_name",competitionName);
           }
           int count = competitionInfoService.count(competitionInfoQueryWrapper);
           if (count>0){
               return Result.error().message("申请的项目名称已存在请重新申请");
           }
           if (!StringUtils.isEmpty(competitionInfo.getTeacherNumber())){
               //得到组织员姓名
               competitionInfo.setCompetitionOrganizer(competitionInfoService.getTeacherNameByNumber(competitionInfo.getTeacherNumber()));
           }
           competitionInfo.setReplaceCourse(String.join("/", competitionInfo.getReplaceCourseList()));
           boolean save = competitionInfoService.save(competitionInfo);
           if (!save){
               return Result.error().message("申请失败");
           }
           return Result.ok().data("competitionId",UUID).message("申请成功");
       }

       @ApiOperation("根据竞赛ID删除竞赛")
       @DeleteMapping("/deleteCompetitionById/{competitionId}")
       public Result deleteCompetitionById(@ApiParam(required = true,value = "竞赛ID")
                                      @PathVariable(value = "competitionId")String competitionId){
           QueryWrapper<CompetitionInfo> competitionInfoQueryWrapper=new QueryWrapper<>();
           competitionInfoQueryWrapper.eq("id",competitionId);
           boolean remove = competitionInfoService.remove(competitionInfoQueryWrapper);
           if (!remove){
               return Result.error().message("删除的竞赛不存在");
           }
           return Result.ok().message("竞赛被成功移除");
       }



       @ApiOperation("根据竞赛ID修改竞赛信息")
       @PostMapping("/updateCompetitionInfo")
       public Result updateComInfoById(@RequestBody CompetitionInfo competitionInfo) {
           if (!StringUtils.isEmpty(competitionInfo.getTeacherNumber())){
               competitionInfo.setCompetitionOrganizer(competitionInfoService.getTeacherNameByNumber(competitionInfo.getTeacherNumber()));
           }
           competitionInfo.setReplaceCourse(String.join("/",competitionInfo.getReplaceCourseList()));
           boolean b = competitionInfoService.updateById(competitionInfo);
           if (!b){
               return Result.error().message("竞赛信息修改失败");
           }
           return Result.ok().message("成功修改竞赛信息");
       }



       @ApiOperation("服务调用修改竞赛组织员信息")
       @PostMapping("/updateCompetitionInfoByTeacherNumber")
       public Boolean updateCompetitionInfoByTeacherNumber(@RequestBody Teacher teacher){
           CompetitionInfo competitionInfo = competitionInfoService.getOne(new QueryWrapper<CompetitionInfo>().eq("teacher_number", teacher.getNumber()));
           if (!StringUtils.isEmpty(competitionInfo)){
                   competitionInfo.setCompetitionOrganizer(teacher.getName());
                   competitionInfo.setTeacherNumber(teacher.getNumber());
                   competitionInfoService.updateById(competitionInfo);
               return true;
           } else {
               return false;
           }
       }



       @ApiOperation("分页条件查询竞赛")
       @PostMapping("/findComByQueryPage/{current}/{limit}")
       public Result findComByQueryPage(@ApiParam(required = true,value = "当前页")
                                   @PathVariable(value = "current") long current,
                                        @ApiParam(required = true,value = "每页记录数")
                                   @PathVariable(value = "limit") long limit,
                                        @RequestBody(required = false) CompetitionInfoQuery competitionInfoQuery){
           Map<String,Object> map=competitionInfoService.findCompetitionByQueryPage(current,limit,competitionInfoQuery);
           long total = (long) map.get("total");
           List<CompetitionInfo> records = (List<CompetitionInfo>) map.get("records");
           if (total<=0){
               return Result.ok().data("records",null).data("total",0).message("暂无此纪录存在");
           }
           return Result.ok().data("total",total).data("records",records);
       }


    @ApiOperation("学生-分页条件查询竞赛")
    @PostMapping("/getAllComByQueryPage/{current}/{limit}")
    public Result getAllComByQueryPage(@ApiParam(required = true,value = "当前页")
                                     @PathVariable(value = "current") long current,
                                     @ApiParam(required = true,value = "每页记录数")
                                     @PathVariable(value = "limit") long limit,
                                     @RequestBody(required = false) CompetitionInfoQuery competitionInfoQuery){
        Map<String,Object> map=competitionInfoService.getAllComByQueryPage(current,limit,competitionInfoQuery);
        long total = (long) map.get("total");
        List<CompetitionInfo> records = (List<CompetitionInfo>) map.get("records");
        if (total<=0){
            return Result.ok().data("records",null).data("total",0).message("暂无此纪录存在");
        }
        return Result.ok().data("total",total).data("records",records);
    }



       @ApiOperation("根据竞赛ID查询竞赛信息")
       @GetMapping("/getOneCom/{comId}")
       public Result getOneCom(@ApiParam(required = true)
                          @PathVariable(value = "comId")String comId){
           CompetitionInfo byId = competitionInfoService.getById(comId);
           byId.setBegintime(CompetitionExcelByHutoolUtils.parseTimeToString(byId.getCompetitionBegin()));
           byId.setEndtime(CompetitionExcelByHutoolUtils.parseTimeToString(byId.getCompetitionEnd()));
           String[] split = byId.getReplaceCourse().split("/");
           byId.setReplaceCourseList(split);
           return Result.ok().data("competitionInfo",byId);
       }


       @ApiOperation("通过服务调用查找课程类别")
       @GetMapping("/getCourseType")
       public Result getCourseType(){
           Result courseType = courseClient.getCourseType();
           Map<String, Object> data = courseType.getData();
           return Result.ok().data("data",data);
       }

       @ApiOperation("通过服务调用查找所有的竞赛组织员")
       @GetMapping("/getAllOrganizer")
       public Result getAllOrganizer(){
           Result allTeacherByRole = courseClient.getAllTeacherByRole();
           Map<String, Object> data = allTeacherByRole.getData();
           return Result.ok().data("data",data);
       }


       @ApiOperation("通过服务调用查询所有的教师部门")
       @GetMapping("/getAllTeacherDepartment")
       public Result getAllTeacherDepartment(){
           Result allTeacherDepartment = courseClient.getAllTeacherDepartment();
           Map<String, Object> data = allTeacherDepartment.getData();
           return Result.ok().data("data",data);
       }


       @ApiOperation("导出选中的竞赛申请信息")
       @PostMapping("/outPutCompetition/{fileName}")
       public Result outPutCompetition(HttpServletResponse response,
                                       @PathVariable(value = "fileName")String fileName,
                                       @RequestBody List<CompetitionInfo> competitionInfoList){
           CompetitionExcelByHutoolUtils.downloadCompetitionExcel(response,fileName,competitionInfoList);
           return Result.ok();
    }

}

